package o2o.web.actions.order.user;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.JYPageUtils;
import com.jinyou.utils.common.ObjectUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.order.postman.PostmanOrderMemoryMan;
import o2o.cache.order.shop.ShopOrderMemoryMan;
import o2o.cache.order.user.UserOrderMemoryMan;
import o2o.cache.order.user.UserOrderMemoryMan2;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.*;
import o2o.dao.PO.shop.FilterConditionUtils;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.order.OrderGoodsVO;
import o2o.dao.VO.order.OrderInfoVO;
import o2o.dao.VO.order.OrderPostmanTroubleVO;
import o2o.dao.VO.order.REFUND_APPLY_STATUS;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.utils.CommonUtils;
import o2o.web.actions.order.OrderListMan;
import o2o.web.actions.order.OrderMan;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

import static o2o.web.actions.order.OrderMan.getOrderDetail;

//订单
@Controller
public class UserOrderListAction {


    //--------------------------------------- 用户

    // 待取货  待配送 待评价 订单数量
    @RequestMapping("/user/order/state/count")
    @ResponseBody
    public String order_list_count(String sysAppKey, String token, String orderTypes) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.successResult();
        }
        Set<Integer> orderSet = null;
        if (ValidateUtil.isNotNull(orderTypes)) {
            orderSet = CommonUtils.splitToSet(orderTypes, Integer.class);
        }
        Map<String, Integer> map = UserOrderMan.getOrderCountByType(sysAppKey, user, orderSet);
        return AjaxResult.successResult(map);
    }

    //用户获取所有订单
    @RequestMapping(method = RequestMethod.POST, value = "/order/list")
    @ResponseBody
    public String order_list(String token, Integer orderType, Long shopId, Long createTime, Integer size, Integer isAgentPayOrder,
                             Integer type) { // type  0 未  1 未评论的 2 待支付的 4 退款单 8 16 32待使用
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (null == size) {
            size = 20;
        }
        List<OrderInfo> list = UserOrderMemoryMan.listOfUser(user.getUsername(), orderType, createTime, size, isAgentPayOrder, type); // type  0 未  1 未评论的 2 待支付的 4 退款单
        if (null == list) {
            return AjaxResult.successResult(0, list);
        }
        List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
        for (int i = 0; i < list.size(); i++) {
            OrderInfoVO infoVO = new OrderInfoVO();
            try {
                ObjectUtils.copyPropertiesExclude(list.get(i), infoVO, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (null == infoVO) {
                continue;
            }
            // 根据店铺筛选
            if (ValidateUtil.isID(shopId) && shopId - infoVO.getShopId() != 0) {
                continue;
            }
            if (ValidateUtil.isNotNull(infoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(infoVO.getShopImageUrl())) {
//                infoVO.setShopImageUrl(Common.imageUrl + infoVO.getShopImageUrl());
                infoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getShopImageUrl());
            }

            // 整合商品信息
            if (!ValidateUtil.isAbsList(infoVO.getGoods())) {
                infoVO.setGoods(UserOrderMan.listOfOrderGoodsByOrderNo(infoVO.getOrderNo()));
            }
            voList.add(infoVO);
        }
        return AjaxResult.successResult(voList.size(), voList);
    }

    /**
     * 用户 获取进行进行中的订单
     *
     * @param token
     * @param orderType
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/user/order/ing/list")
    @ResponseBody
    public String order_ing_list(String token, Integer orderType,
                                 Integer isZiqu, // 0配送  1自取  2全部
                                 Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (page == null) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }
        List<OrderInfo> orderInfoList = UserOrderMemoryMan.listOfUserIngOrder(user.getUsername(), orderType,
                isZiqu);
        if (ValidateUtil.isAbsList(orderInfoList)) {
            // 排序
            Collections.sort(orderInfoList, Comparator.comparingLong(OrderInfo::getCreateTime).reversed());
            JYPageUtils.PageList pageList = JYPageUtils.getList(orderInfoList, page, size);
            List<OrderInfoVO> list = new ArrayList<>();
            for (OrderInfo orderInfo : (List<OrderInfo>) pageList.list) {
                OrderInfoVO infoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(orderInfo, infoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 店铺头像
                if (ValidateUtil.isNotNull(infoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(infoVO.getShopImageUrl())) {
                    infoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getShopImageUrl());
                }
                // 骑手头像
                if (ValidateUtil.isNotNull(infoVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(infoVO.getPostmanImageUrl())) {
                    infoVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getPostmanImageUrl());
                }
                list.add(infoVO);
            }
            if (ValidateUtil.isAbsList(list)) {
                return AjaxResult.successResult(pageList.totalCount, list.size(), list);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }


    /**
     * 分页获取-》用户筛选订单
     *
     * @param token
     * @param orderType
     * @param page
     * @param size
     * @param startTime
     * @param endTime
     * @param isUnComment
     * @param isWaitPay
     * @param isRefund
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/order/orderType/list")
    @ResponseBody
    public String order_orderType_list(String token, Integer orderType,
                                       Integer page,
                                       Integer size,
                                       Long startTime,
                                       Long endTime,
                                       Integer isUnComment,
                                       Integer isWaitPay,
                                       Integer isRefund,
                                       Integer type) { // type  0 未  1 未评论的 2 待支付的 4 退款单 8 待取货 16 待配送
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (userInfo == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!ValidateUtil.isAbsInteger(page)) {
            page = 1;
        }
        if (!ValidateUtil.isAbsInteger(size)) {
            size = 20;
        }
        List<OrderInfo> infoList = UserOrderMemoryMan.listOfUser(userInfo.getUsername(), orderType);
        if (ValidateUtil.isAbsList(infoList)) {
            List<OrderInfo> list = new ArrayList();
            for (OrderInfo info : infoList) {
                // 用户已经删除的要去除
                if (info.getUserDel() == 1) {
                    continue;
                }
                // 时间
                if (ValidateUtil.isAbsLong(startTime) && startTime >= info.getCreateTime()) {
                    continue;
                }
                if (ValidateUtil.isAbsLong(endTime) && endTime <= info.getCreateTime()) {
                    continue;
                }
                if (type != null && type != 0) {
                    if (!((type & USER_ORDER_FILTER.BEAK_ORDER) > 0 || (type & USER_ORDER_FILTER.WAITING_FOR_PICK) > 0 || (type & USER_ORDER_FILTER.WAITING_FOR_POST) > 0 || (type & USER_ORDER_FILTER.TO_BE_PAID) > 0 || (type & USER_ORDER_FILTER.UN_COMMENT) > 0)) {
                        return AjaxResult.errorResult("请选择请求类型");
                    }
                    if ((type & USER_ORDER_FILTER.UN_COMMENT) > 0) {
                        if (info.getOrderStatus() == ORDER_STATUS.OVER && info.getIsComment() == 0) {

                        } else {
                            continue;
                        }
                    }
                    if ((type & USER_ORDER_FILTER.TO_BE_PAID) > 0) {
                        if (info.getOrderStatus() == ORDER_STATUS.SUBMIT && info.getIsPaid() == 0) {

                        } else {
                            continue;
                        }
                    }
                    if ((type & USER_ORDER_FILTER.BEAK_ORDER) > 0) {
                        if (info.getIsRefundApply() == REFUND_APPLY_STATUS.APPLY
                                || info.getIsRefundApply() == REFUND_APPLY_STATUS.PASS
                                || info.getIsPartCancelApply() == REFUND_APPLY_STATUS.PASS
                                || ((info.getIsPartCancelApply() == REFUND_APPLY_STATUS.APPLY)
                                && info.getOrderStatus() != ORDER_STATUS.OVER
                                && info.getOrderStatus() != ORDER_STATUS.POSTMAN_FINISH
                                && info.getOrderStatus() != ORDER_STATUS.SHOP_FINISH)
                        ) {

                        } else {
                            continue;
                        }
                    }
                    // 待取货
                    if ((type & USER_ORDER_FILTER.WAITING_FOR_PICK) > 0) {
                        if (info.getOrderStatus() == ORDER_STATUS.PAYED
                                || info.getOrderStatus() == ORDER_STATUS.SHOP_SURE
                                || info.getOrderStatus() == ORDER_STATUS.SHOP_READY
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_DAODIAN
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_ZHIDING
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_ZD_SURE_BEFORE_SHOP
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_REFUSED
                                || info.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_SUER
                                || info.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_DAODIAN
                                || info.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_INNER_SHOP) {

                        } else {
                            continue;
                        }
                    }
                    // 待配送
                    if ((type & USER_ORDER_FILTER.WAITING_FOR_POST) > 0) {
                        if (info.getOrderStatus() == ORDER_STATUS.SHOP_PUSH_GOODS
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_PULL_GOODS
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_PICK_POINT
                                || info.getOrderStatus() == ORDER_STATUS.PEISONG
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_FINISH
                                || info.getOrderStatus() == ORDER_STATUS.SHOP_FINISH
                                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_PICK_POINT
                                || info.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_PULL_GOODS) {

                        } else {
                            continue;
                        }
                    }
                } else {
                    // 未评价的
                    if (isUnComment != null && isUnComment == 1) {
                        if (info.getOrderStatus() == ORDER_STATUS.OVER && info.getIsComment() == 0) {

                        } else {
                            continue;
                        }
                    }
                    // isWaitPay 待支付的
                    if (isWaitPay != null && isWaitPay == 1) {
                        if (info.getOrderStatus() == ORDER_STATUS.SUBMIT && info.getIsPaid() == 0) {

                        } else {
                            continue;
                        }
                    }
                    // isRefund 退款的
                    if (isRefund != null && isRefund == 1) {
                        if (info.getIsRefundApply() == REFUND_APPLY_STATUS.APPLY
                                || info.getIsRefundApply() == REFUND_APPLY_STATUS.PASS
                                || info.getIsPartCancelApply() == REFUND_APPLY_STATUS.PASS
                                || ((info.getIsPartCancelApply() == REFUND_APPLY_STATUS.APPLY)
                                && info.getOrderStatus() != ORDER_STATUS.OVER
                                && info.getOrderStatus() != ORDER_STATUS.POSTMAN_FINISH
                                && info.getOrderStatus() != ORDER_STATUS.SHOP_FINISH)
                        ) {

                        } else {
                            continue;
                        }
                    }
                }
                list.add(info);
            }
            if (!ValidateUtil.isAbsList(list)) {
                return AjaxResult.successResult(null, 0);
            }
            JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
            List<OrderInfoVO> infoVOList = new ArrayList<>();

            for (OrderInfo info : ((List<OrderInfo>) (pageList.list))) {
                if (info == null) {
                    continue;
                }
                OrderInfoVO infoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(info, infoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (null == infoVO) {
                    continue;
                }
                if (ValidateUtil.isNotNetUrl(infoVO.getShopImageUrl())) {
                    infoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getShopImageUrl());
                }

                infoVOList.add(infoVO);
            }
            return AjaxResult.successResult(infoVOList, pageList.totalCount);
        }
        return AjaxResult.successResult(null, 0);
    }


    // 好管家用户获取所有订单
    //分页 （显示跑腿订单）
    @RequestMapping(method = RequestMethod.POST, value = "/order/list/v2")
    @ResponseBody
    public String order_list_V2(String token, Integer orderType, Long shopId, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (null == size) {
            size = 20;
        }
        List<OrderInfo> list = UserOrderMemoryMan2.listOfUserV2(user.getUsername(), orderType, createTime, size);
        if (null == list) {
            return AjaxResult.successResult(0, list);
        }
        List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
        for (int i = 0; i < list.size(); i++) {
            OrderInfoVO infoVO = new OrderInfoVO();
            try {
                ObjectUtils.copyPropertiesExclude(list.get(i), infoVO, null);
            } catch (Exception e) {
                e.printStackTrace();
            }


            //店铺信息存起来
            //店铺名称
//            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(infoVO.getShopId());
//            infoVO.setShopName(shopInfo.getShopName());
//            infoVO.setShopImageUrl(shopInfo.getImageUrl());

            //收货地址
//            UserAddress userAddress = UserAddressMemory.getInstance().getAddressInfo(infoVO.getDeliveryId());

            if (null == infoVO) {
                continue;
            }
            // 根据店铺筛选
            if (ValidateUtil.isID(shopId) && shopId - infoVO.getShopId() != 0) {
                continue;
            }
            if (ValidateUtil.isNotNetUrl(infoVO.getShopImageUrl())) {
//                infoVO.setShopImageUrl(Common.imageUrl + infoVO.getShopImageUrl());
                infoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getShopImageUrl());
            }


            voList.add(infoVO);
        }
        return AjaxResult.successResult(voList.size(), voList);
    }

    //已完成的订单列表
    @RequestMapping(method = RequestMethod.POST, value = "user/order/finish/list")
    @ResponseBody
    public String order_user_finish_list(String token,
                                         Integer isZiqu, // 0配送  1自取  2全部
                                         String city, String county, String region, Long createTime, int size, @RequestParam(defaultValue = "0") Integer groupOrder) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        List<OrderInfo> list = UserOrderMemoryMan.listOfUserFinish(user.getUsername(), createTime, size, isZiqu);
        if (ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(list.size(), list);
        }

        return AjaxResult.successResult(0, null);
    }

    //已完成的订单列表-(废弃)
    @RequestMapping(method = RequestMethod.POST, value = "/order/finish/list")
    @ResponseBody
    public String order_finish_list(String token,
                                    Integer isZiqu, // 0配送  1自取  2全部
                                    String city, String county, String region, Long createTime, int size, @RequestParam(defaultValue = "0") Integer groupOrder) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        List<OrderInfo> list = null;
        //用户类型
        switch (user.getUserType()) {
            case UserType.USER: {//普通用户
                list = UserOrderMemoryMan.listOfUserFinish(user.getUsername(), createTime, size, isZiqu);
            }
            break;
            case UserType.SUPER_ADMIN:
            case UserType.ADMIN: {//管理员
//                QueryCondition query = QueryCondition.getInstance();
//                Expression expression = Expression.getInstance();
//                expression.addChild("delFlag", 0);//所有未删除的
//                if (createTime > 0) {
//                    expression.addChild("createTime", "<", createTime);//所有未删除的
//                }
//                if (ValidateUtil.isNotNull(city)) {
//                    expression.addChild("city", city);//省
//                }
//                expression.addChild("orderStatus", ORDER_STATUS.OVER);//已完成的订单
//                query.addCondition(expression);
//                query.addOrders("createTime", "desc");
//                query.setSize(size);
//                String sql = DaoUtils.getSql(PojoTables.OrderInfo, query);

                String cityStr = "";
                if (ValidateUtil.isNotNull(city)) {
                    cityStr = " and city = '" + city + "'";
                }
                String countyStr = "";
                if (ValidateUtil.isNotNull(county)) {
                    county = " and county = '" + county + "'";
                }
                String regionStr = "";
                if (ValidateUtil.isNotNull(region)) {
                    regionStr = " and region = '" + region + "'";
                }
                String createTimeStr = "";
                if (createTime > 0) {
                    createTimeStr = " and createTime <" + createTime;
                }

                StringBuilder sb = new StringBuilder();
                sb.append("SELECT a.* ")
                        .append(" FROM ").append(PojoTables.OrderInfo).append(" a ")
                        .append(" LEFT JOIN ").append(PojoTables.ShopInfo).append(" b ON a.shopId = b.id")
                        .append(" WHERE a.delFlag = 0  and orderStatus = ").append(ORDER_STATUS.OVER)
                        .append(cityStr).append(countyStr).append(regionStr)
                        .append(createTimeStr)
                        .append(" limit 0,").append(size);
                try {
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            break;
            case UserType.POSTMAN: {//配送员
                list = PostmanOrderMemoryMan.listOfPostmanFinish(user.getUsername(), createTime, size);
            }
            break;
            case UserType.SHOP_OWNER: {//店主
                ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
                if (null != shopInfo) {
                    FilterConditionUtils utils = FilterConditionUtils.getInstance().setGroupOrder(groupOrder);
                    list = ShopOrderMemoryMan.listOfShopFinish(shopInfo.getId(), shopInfo.getIsSelfPost(), createTime, size, utils);
                }
            }
            break;
        }
        if (ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(list.size(), list);
        }

        return AjaxResult.successResult(0, null);
    }

    //进行中的订单
    @RequestMapping(method = RequestMethod.POST, value = "/order/ing/list")
    @ResponseBody
    public String order_ing_list(String token,
                                 Integer isZiqu, // 0配送  1自取  2全部
                                 String city, String county, String region, Long createTime, Integer size, Integer isLoadMore, @RequestParam(defaultValue = "0") Integer groupOrder) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        if (null == isLoadMore) {
            if (createTime > 0) {
                // 老版本的，传了非0时间戳则是加载更多
                isLoadMore = 1;
            } else {
                isLoadMore = 0;
            }
        }

        List<OrderInfo> list = null;
        //用户类型
        switch (user.getUserType()) {
            case UserType.USER: {//普通用户
                list = UserOrderMemoryMan.listOfUserIngOrder(user.getUsername(), createTime, size, isZiqu);
            }
            break;
            case UserType.SUPER_ADMIN:
            case UserType.ADMIN: {//管理员
                String cityStr = "";
                if (ValidateUtil.isNotNull(city)) {
                    cityStr = " and city = '" + city + "'";
                }
                String countyStr = "";
                if (ValidateUtil.isNotNull(county)) {
                    countyStr = " and county = '" + county + "'";
                }
                String regionStr = "";
                if (ValidateUtil.isNotNull(region)) {
                    regionStr = " and region = '" + region + "'";
                }
                String createTimeStr = "";
                if (createTime > 0) {
                    createTimeStr = " and createTime <" + createTime;
                }

                StringBuilder sb = new StringBuilder();
                sb.append("SELECT a.* ")
                        .append(" FROM ").append(PojoTables.OrderInfo).append(" a ")
                        .append(" LEFT JOIN ").append(PojoTables.ShopInfo).append(" b ON a.shopId = b.id")
                        .append(" WHERE a.delFlag = 0  and orderStatus != ").append(ORDER_STATUS.OVER)
                        .append(cityStr).append(countyStr).append(regionStr)
                        .append(createTimeStr)
                        .append(" limit 0,").append(size);
                try {
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            break;
            case UserType.POSTMAN: {//配送员
                list = PostmanOrderMemoryMan.listOfPostmanIng(user.getUsername(), createTime, size);
            }
            break;
            case UserType.SHOP_OWNER: {//店主
                ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
                if (null != shopInfo) {
                    FilterConditionUtils utils = FilterConditionUtils.getInstance().setGroupOrder(groupOrder);
                    list = ShopOrderMemoryMan.listOfShopIng(shopInfo.getId(), shopInfo.getIsSelfPost(), createTime, size, isLoadMore, utils);
                }
            }
            break;
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, true);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }


        return AjaxResult.successResult(0, null);
    }
    //待支付订单
    //待收货订单


    //-------------------------
    //转化为vo  list
//    private List<OrderInfoVO> convertToVo(List<OrderInfo> list) {
//        if (ValidateUtil.isAbsList(list)) {
//            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
//            for (int i = 0; i < list.size(); i++) {
//                if (null == list.get(i)) {
//                    continue;
//                }
//                OrderInfoVO orderInfoVO = new OrderInfoVO();
//                try {
//                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    continue;
//                }
//                if (null == orderInfoVO) {
//                    continue;
//                }
//
//                if (null == orderInfoVO.getGoods() && ValidateUtil.isNotNull(orderInfoVO.getOrderNo())) {
//                    List<OrderGoods> orderGoods = OrderGoodsMemory.getInstance().listOfOrderNo(orderInfoVO.getOrderNo());
//                    if (ValidateUtil.isAbsList(orderGoods)) {
//                        List<OrderGoodsVO> goodsVOList = new ArrayList<OrderGoodsVO>();
//                        for (int j = 0; j < orderGoods.size(); j++) {
//                            if (null == orderGoods.get(j)) {
//                                continue;
//                            }
//                            OrderGoodsVO orderGoodsVO = new OrderGoodsVO();
//                            try {
//                                ObjectUtils.copyPropertiesExclude(orderGoods.get(j), orderGoodsVO, null);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                                continue;
//                            }
//                            if (null == orderGoodsVO) {
//                                continue;
//                            }
//                            goodsVOList.add(orderGoodsVO);
//                        }
//                        if (ValidateUtil.isAbsList(goodsVOList)) {
//                            orderInfoVO.setGoods(goodsVOList);
//                        }
//                    }
//                }
//
//                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
////                    orderInfoVO.setShopImageUrl(Common.imageUrl + orderInfoVO.getShopImageUrl());
//                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
//                }
//                if (ValidateUtil.isNotNull(orderInfoVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getPostmanImageUrl())) {
////                    orderInfoVO.setPostmanImageUrl(Common.imageUrl + orderInfoVO.getPostmanImageUrl());
//                    orderInfoVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getPostmanImageUrl());
//                }
//
//                voList.add(orderInfoVO);
//            }
//            if (ValidateUtil.isAbsList(voList)) {
//                return voList;
//            }
//        }
//        return null;
//    }

    //获取标签
//    private List<OrderGoodsLabelVO> listOfOrderNO(String orderNo) {
//        if (ValidateUtil.isNull(orderNo)) {
//            return null;
//        }
//        List<OrderGoodsLabel> list = OrderGoodsLabelMemory.getInstance().listOfOrderNo(orderNo);
//        if (!ValidateUtil.isAbsList(list)) {
//            return null;
//        }
//        List<OrderGoodsLabelVO> voList = new ArrayList<>();
//        for (int i = 0; i < list.size(); i++) {
//            if (null == list.get(i)) {
//                continue;
//            }
//
//            OrderGoodsLabelVO vo = new OrderGoodsLabelVO();
//            try {
//                ObjectUtils.copyPropertiesExclude(list.get(i), vo, null);
//            } catch (Exception e) {
//                e.printStackTrace();
//                continue;
//            }
//            voList.add(vo);
//        }
//
//        return voList;
//    }
//
//    //排序
//    private List<OrderInfo> sort(List<OrderInfo> list) {
//        JYListSort.sortDesc(list, "createTime");
//        return list;
//    }



    /**
     * 用户订单搜索
     */
    @RequestMapping("/user/order/search")
    @ResponseBody
    public String userOrderSearch(String token, String params, String orderTypes, Long startTime, Long endTime, Integer page, Integer size) {
        if (SYS_SETTINGS.USER_ORDER_CAN_SEARCH == null || SYS_SETTINGS.USER_ORDER_CAN_SEARCH != 1) {
            return AjaxResult.successResult(null, 0);
        }
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(params)) {
            return AjaxResult.successResult(null, 0);
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 15;
        }
        Set<Integer> orderTypeSet = null;
        if (ValidateUtil.isNotNull(orderTypes)) {
            orderTypeSet = CommonUtils.splitToSet(orderTypes, Integer.class);
        } else {
            orderTypeSet = new HashSet<>();
            orderTypeSet.add(ORDER_TYPE.SHOP_GOODS);
            orderTypeSet.add(ORDER_TYPE.GROUP_ORDER);
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" from ").append(PojoTables.OrderInfo).append(" as OI LEFT JOIN ").append(PojoTables.OrderGoods)
                .append(" as OG ON OI.orderNo = OG.orderNo ")
                .append(" where OI.delFlag = 0 and OI.userDel = 0 ");
        if (orderTypeSet != null && !orderTypeSet.isEmpty()) {
            if (orderTypeSet.size() == 1) {
                sql.append(" and OI.orderType =").append(orderTypeSet.iterator().next());
            } else {
                sql.append(" and OI.orderType in (").append(StringUtils.join(orderTypeSet, ",")).append(") ");
            }
        }
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and OI.createTime > ").append(startTime);
        }
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and OI.createTime < ").append(endTime);
        }
        sql.append(" and (OI.shopName like '%").append(params).append("%' or  OG.name like '%").append(params).append("%' or OI.orderNo like '%").append(params).append("%') ");
        sql.append(" and OI.orderNo not like 'S%' ");
        sql.append(" and username = '").append(user.getUsername()).append("' ");

        // counts
        String countSQL = " select count(DISTINCT(OI.orderNo)) as counts " + sql.toString();
        // order_info
        String orderSQL = " select DISTINCT(OI.orderNo) as orderNo2, OI.*  " + sql.toString()
                + " order By orderNo2  desc limit " + (page - 1) * size + "," + size;
        Long counts = 0L;
        List<OrderInfoVO> orderInfoList = null;
        try {
            counts = UserDaoSql.getInstance().getCount(countSQL);
            orderInfoList = (List<OrderInfoVO>) UserDaoSql.getInstance().list(OrderInfoVO.class, orderSQL);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.successResult(null, 0);
        }
        if (!ValidateUtil.isAbsList(orderInfoList)) {
            return AjaxResult.successResult(null, counts);
        }
        Set<String> orderNoSet = orderInfoList.stream().map(item -> "'" + item.getOrderNo() + "'").collect(Collectors.toSet());
        // goods
        String orderGoodsSQL = " select * from " + PojoTables.OrderGoods + " where delFlag = 0 and orderNo in (" + StringUtils.join(orderNoSet, ",") + ") ";
        List<OrderGoodsVO> orderGoodsList = null;
        try {
            orderGoodsList = (List<OrderGoodsVO>) UserDaoSql.getInstance().list(OrderGoodsVO.class, orderGoodsSQL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(orderGoodsList)) {
            Map<String, List<OrderGoodsVO>> orderGoodsMap = orderGoodsList.stream().map(item -> {
                if (ValidateUtil.isNotNull(item.getImageUrl()) && ValidateUtil.isNotNetUrl(item.getImageUrl())) {
                    item.setImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + item.getImageUrl());
                }
                return item;
            }).collect(Collectors.groupingBy(OrderGoodsVO::getOrderNo));
            orderInfoList = orderInfoList.stream().map(item -> {
                if (ValidateUtil.isNotNull(item.getShopImageUrl()) && ValidateUtil.isNotNetUrl(item.getShopImageUrl())) {
                    item.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + item.getShopImageUrl());
                }
                List<OrderGoodsVO> goodsVOS = orderGoodsMap.get(item.getOrderNo());
                if (ValidateUtil.isAbsList(goodsVOS)) {
                    item.setGoods(goodsVOS);
                }
                return item;
            }).collect(Collectors.toList());
        }
        return AjaxResult.successResult(orderInfoList, counts);
    }

    //获取异常订单详情列表
    @RequestMapping("/user/order/trouble/info/list")
    @ResponseBody
    public String userOrderTroubleInfoList(String token, String orderNo) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("orderNo", orderNo);
        query.addCondition(expression);
        query.addOrders("createTime", "desc");
        query.addOrders("orderNo", "desc");
        String sql = DaoUtils.getSql(PojoTables.ORDER_POSTMAN_TROUBLE, query);
        List<OrderPostmanTrouble> list = null;
        try {
            list = (List<OrderPostmanTrouble>) UserDaoSql.getInstance().list(OrderPostmanTrouble.class, sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            List<OrderPostmanTroubleVO> voList = new ArrayList<>();
            list.forEach(item -> {
                OrderPostmanTroubleVO vo = new OrderPostmanTroubleVO();
                BeanUtils.copyProperties(item, vo);
                if (ValidateUtil.isNotNull(vo.getUsername())) {
                    UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
                    if (null != userInfo) {
                        vo.setName(userInfo.getName());
                        vo.setSignPhoto(userInfo.getSignPhoto());
                    }
                }
                // 查询订单信息
                OrderInfoVO infoVO = null;
                // 聚合订单 ？
                if (OrderMan.isMultipleParentOrder(vo.getOrderNo())) {
                    //订单信息
                    infoVO = OrderMan.getMultipleParentOrderDetail(vo.getOrderNo(), user);
                } else {
                    // 非聚合订单
                    infoVO = getOrderDetail(vo.getOrderNo());
                }
                if (infoVO != null) {
                    vo.setInfoVO(infoVO);
                    vo.setShopName(infoVO.getShopName());
                }
                voList.add(vo);
            });
            return AjaxResult.successResult(voList.size(), voList);
        }
        return AjaxResult.successResult(0, null);
    }

}
